<template>
  <div class="experPage">
    <!-- <div style="color: rgb(27, 76, 184)">
      <div class="addressIcon"></div>
      <span>当前位置：</span>
      <span style="cursor: pointer" @click="returnExper">{{ pageTitle }}管理</span>
      <Icon type="ios-arrow-forward" color="rgb(27, 76, 184)" size="16" />
      <span style="color: #333" v-text="reciveData.ecname"></span>
    </div> -->
    <Row>
      <Col span="18" style="height: calc(100vh - 148px);padding-bottom: 25px;background-color: var(--card-body-bgcolor);border-radius: 10px;padding: 30px 0">
        <div class="class-top">
          <div class="class-title-wrap">
            <div class="class-title" v-if="reciveData.expType != 2 && reciveData.guide">
              <div
                class="class-title-all"
                :class="{ active: expListText }"
                @click="clickClassText('guide')"
              >
                课件指导书
              </div>
              <div class="class-title-line" :class="{ 'line-active': expLine }"></div>
            </div>
            <div class="class-title" v-if="coursewareLists.length>0">
              <div
                class="class-title-all"
                :class="{ active: coursewareText }"
                @click="clickClassText('courseware')"
              >
                教学课件
              </div>
              <div class="class-title-line" :class="{ 'line-active': coursewareLine }"></div>
            </div>
            <div class="class-title" v-if="reciveData.expType != 2 && videoLists.length>0">
              <div
                class="class-title-all"
                :class="{ active: lessonText }"
                @click="clickClassText('video')"
              >
                教学视频
              </div>
              <div class="class-title-line" :class="{ 'line-active': lessonLine }"></div>
            </div>
            <div class="class-title">
              <div
                class="class-title-all"
                :class="{ active: questionText }"
                @click="clickClassText('question')"
              >
                课后练习
              </div>
              <div class="class-title-line" :class="{ 'line-active': questionLine }"></div>
            </div>
            <div class="class-title" v-if="commentList.length>0">
              <div
                class="class-title-all"
                :class="{ active: commentText }"
                @click="clickClassText('comment')"
              >
                课件评论
              </div>
              <div class="class-title-line" :class="{ 'line-active': commentLine }"></div>
            </div>
            <div class="class-title" v-if="notesList.length>0||videoNotesList.length>0">
              <div
                class="class-title-all"
                :class="{ active: notesText }"
                @click="clickClassText('notes')"
              >
                课件笔记
              </div>
              <div class="class-title-line" :class="{ 'line-active': notesLine }"></div>
            </div>
          </div>
          <div
            style="display: flex;justify-content: flex-start;align-items: center"
            v-show="expListText && reciveData.customType != 1"
          >
            <div
              v-show="showCloseAndOpenBtn"
              class="openCloseIcon flex"
              @click="exptaskclose"
            >
              <Icon type="ios-list" :size="28" style="font-weight: bold;"/>
              <!-- <img :src="closeAll" alt="close" /> -->
              <span>关闭</span>
            </div>
            <div
              v-show="!showCloseAndOpenBtn"
              class="openCloseIcon flex"
              style="margin-left: 20px"
              @click="exptaskexpand"
            >
              <Icon type="ios-list" :size="28" style="font-weight: bold;"/>
              <!-- <img :src="openAll" alt="open" /> -->
              <span>展开</span>
            </div>
          </div>
        </div>
        <Divider />
        <div class="guide-wrap" :style="{ height: contentHei }">
          <template v-if="expListText && reciveData.expType != 2">
            <div v-if="reciveData.customType == 1" style="display: flex;flex-direction: column;">
              <guideIframe
                :type="0"
                :mdPath="reciveData.guide"
                :guideSrc="guideSrc"
                :contentHeiNei="contentHeiNei"
              ></guideIframe>
            </div>
            <div v-else style="height: 100%;">
              <SectionList ref="sectionList" :data="guideList" :showAllBtn="false" :showCloseAndOpenBtn.sync="showCloseAndOpenBtn" :mktype="markType"/>
              <!-- <div class="guidancebookList" v-if="showDataList "> -->
                <!-- <div>
                  <div class="guidancebookdiv" v-for="(value, index) in guideList" :key="index">
                    <div
                      class="guidancebooktitle"
                      @click="guidancebooktitle(index)"
                      data-name="指导书标题"
                    >
                      <img
                        v-if="value.ischeckpoint == 1"
                        title="关键点"
                        height="16"
                        style="float:right;margin:10px;"
                        src="../../../assets/globalIcon/section-key.png"
                      />
                      <div class="openClass" :style="{'background-image': `url(${closeSingle})!important`}"></div>
                      <span v-text="value.sectionname">{{ value.sectionname }}</span>
                    </div>
                    <div
                      class="guidancebookcontent"
                      data-name="指导书内容"
                      style="overflow: hidden; display: block;"
                    >
                      <span>
                        <div
                          v-if="markType != 'markdown'"
                          v-html="xss(escape2Html(value.sectiontext))"
                        ></div>
                        <div v-else v-html="markedData(value.sectiontext)"></div>
                      </span>
                      <Divider
                        dashed
                        v-if="value.sectionQuestionList && value.sectionQuestionList.length > 0"
                      />
                      <div style="display: flex;flex-wrap:wrap;">
                        <QuestionCard
                          v-for="(item, key) in value.sectionQuestionList"
                          :key="item.questionId"
                          :question="item.questionDto"
                          :bordered="true"
                          style="width:350px;margin-right:10px;margin-bottom:10px;flex-shrink:0;"
                      ></QuestionCard>
                      </div>
                    </div>
                  </div>
                </div> -->
              <!-- </div> -->
              <!-- <no-data v-if="showDefImg"></no-data> -->
            </div>
          </template>
          <div v-if="coursewareText || lessonText" style="height: 94%;width: 94%;">
          <ExpVideo
            :contentHeiNei="contentHeiNei"
            :ecid="reciveData.ecid"
            :type="coursewareText ? 'EduPdf' : lessonText ? 'EduVideo' : ''"
            :status="setReBtnStatus()"
            
            ref="expVideos"
          ></ExpVideo>
          </div>
          <ExpQuestion
            :ecid="reciveData.ecid"
            :isPublic="reciveData.isPublic"
            :isOwn="isOwn"
            :status="setReBtnStatus()"
            v-if="questionText"
          ></ExpQuestion>
          <ExpComment
            :experInfo="reciveData"
            :status="setReBtnStatus()"
            v-if="commentText"
          ></ExpComment>
          <ExpNotes :experInfo="reciveData" :status="setReBtnStatus()" v-if="notesText"></ExpNotes>
        </div>
      </Col>
      <Col span="6" style="padding-left: 25px;height: calc(100vh - 148px);">
        <div class="class-info-wrap">
          <div style="position: relative;" :style="{ height: rightTopImgHei }">
            <img
              style="width: 100%;height: 100%;border-radius: 10px;"
              :src="handleImage(this.reciveData.topology)"
              @error="setDefImg"
            />
            <p class="destoryTime" v-if="destroyStatus && deployNum === 3 && proId && leftTime > 0">
              环境销毁倒计时：{{ curTime.h }}:{{ curTime.m }}:{{ curTime.s }}
            </p>
          </div>
          <div
            style="display: flex;justify-content: space-between;align-items:center;width: 100%;"
            v-if="reciveData.expType == 0"
          >
            <div :style="{ width: deployWidth, position: 'relative' }">
              <Button
                :type="btnType"
                size="large"
                long
                style="margin:20px 0;width: 100%"
                :loading="createdLoad"
                @click="creatExperBtn"
              >
                <span v-if="!createdLoad">{{ this.createdVmText }}</span>
                <span v-else>{{ this.processText }}</span>
              </Button>
            </div>
            <Icon
              type="ios-information-circle-outline"
              class="deployErrorBtn"
              title="点击查看错误详情"
              @click.native="getProjectDeployDetail"
              v-if="createdVmText == '重新部署' || errorMessage"
            />
            <Poptip
              confirm
              title="确定要销毁课件机吗？"
              :style="{ width: destroyWidth }"
              @on-ok="destroyBtn"
              class="destroyPop"
            >
              <Button
                type="error"
                size="large"
                v-show="destroyStatus || errorMessage"
                style="margin:20px 0;width: 100%"
                >销毁</Button
              >
            </Poptip>
          </div>
          <div
            class="class-right-info"
            :style="{ height: rightHei, marginTop: reciveData.expType != 0 ? '20px' : '' }"
          >
            <Tooltip
              style="font-size: 16px;font-weight: 600;width: 100%"
              max-width="200"
              :content="this.reciveData.ecname"
              placement="top-start"
            >
              <div
                class="text-ellipsis"
              >
                {{ this.reciveData.ecname }}
              </div>
            </Tooltip>
            <div class="class-right-icon">
              <div class="designIcon"></div>
              <span class="class-right-text">设计师：</span>
              <span>{{ this.reciveData.designer }}</span>
            </div>
            <div class="class-right-icon">
              <div class="visibilyIcon"></div>
              <span class="class-right-text">可见范围：</span>
              <span>{{ handleIsPublic(this.reciveData.isPublic) }}</span>
            </div>
            <div class="class-right-icon">
              <div class="desigTimeIcon"></div>
              <span class="class-right-text">设计时间：</span>
              <span>{{ showTimeNotSecond(this.reciveData.createTime) }}</span>
            </div>
            
            <div class="class-line-div"></div>

            <div class="class-right-icon">
              <span class="class-right-text">难度：</span>
              <span>{{ handleDiffcult(this.reciveData.difficulty) }}</span>
            </div>
            <div class="class-right-icon">
              <span class="class-right-text">方向：</span>
              <span>{{ handleDirection(reciveData.typeCode) }}</span>
            </div>
            <div class="class-right-icon">
              <span class="class-right-text">类型：</span>
              <span>{{ handleTypeCode(reciveData.typeCode) }}</span>
            </div>
            <div class="class-right-icon">
              <span class="class-right-text">模式：</span>
              <span>{{ handleExperType(reciveData.expType) }}</span>
            </div>
            <div class="class-right-icon">
              <span class="class-right-text">标签：</span>
              <span>{{
                !reciveData.labels || reciveData.labels == 'null'
                  ? '-'
                  : reciveData.labels.replaceAll(';', ',')
              }}</span>
            </div>
            <div class="class-right-icon" style="align-items: flex-start;">
              <span class="class-right-text">描述：</span>
              <span
                style="color: #999;line-height: 2"
                v-text="reciveData.description || '-'"
              ></span>
              <!--  -->
            </div>

            <div class="class-line-div"></div>
            
            <div class="class-right-icon-rule">
              <span>已学规则：</span><br />
              <div v-if="reciveData.expType == 0">
                <span
                  >1.完成课件机创建,并进入环境进行课件操作<span style="color:#f70"
                    >(至少{{ opVmTime }}分钟)</span
                  ></span
                ><br />
                <span>2.课件指导书所有步骤都完成或预览完成为已学</span><br />
                <span>3.完成视频播放</span><br />
                <span>(注：视频没有的情况，只需要完成1和2即可)</span>
              </div>
              <div v-if="reciveData.expType == 1">
                <span>1.课件指导书所有步骤都完成或预览完成为已学</span><br />
                <span>2.完成视频播放</span><br />
                <span>(注：指导书没有的情况，只需要完成视频播放即可)</span>
              </div>
              <div v-if="reciveData.expType == 2">
                <span>完成课件预览</span>
              </div>
            </div>
          </div>
        </div>
      </Col>
    </Row>
    <Modal
      v-model="deployErrorDetailModal"
      title="环境部署错误详情"
      :width="errorDetailData.length > 0 ? 80 : 20"
      footer-hide
    >
      <h3 v-if="errorMessage && errorDetailData.length == 0" style="color:#f00">
        <span v-html="errorMessage">{{ errorMessage }}</span>
      </h3>
      <Table
        border
        ref=""
        :columns="errorDetailColumns"
        :data="errorDetailData"
        stripe
        v-if="errorDetailData.length > 0"
      ></Table>
      <span v-if="!errorMessage && errorDetailData.length == 0">未获取到错误信息</span>
    </Modal>
  </div>
</template>
<script>
import $ from 'jquery';
import encryption from '@/libs/encryption.js';
import defaultImg from '@/assets/globalIcon/course.jpg';
import {
  sectionList_new,
  querySectionQuestion,
  donwLoadMdFile,
  getGuideInfoByID_new
} from '@/api/guide.js';
import { getstatusbyprjid } from '@/api/drill';
import { experType, getDictInfoByName } from '@/api/dict.js';
import {
  expEnv,
  queryInterval,
  destroyExper,
  creatExper,
  experimentDetail,
  getProjectDeployDetail,
  getVideoDetail,
  getTime,
  getCommentList,
  getNotesList
} from '@/api/selfStudy/courseExp.js';
import ExpQuestion from './expQuestion.vue';
import ExpVideo from './expVideo.vue';
import ExpComment from './expComment.vue';
import ExpNotes from './expNotes.vue';
import guideIframe from './guideIframe.vue';
import { escape2Html, showTimeNotSecond} from '@/libs/utils';
import { marked } from 'marked';
import { nextTick } from 'vue';
import QuestionCard from '@/components/question-list/question-card.vue';
import SectionList from '@/components/common/guide-section-list'
import { mapState } from 'vuex'
export default {
  components: { ExpVideo, ExpComment, ExpNotes, guideIframe, ExpQuestion, QuestionCard,SectionList },
  name:'experdetails',
  data() {
    return {
      showTimeNotSecond,
      markType: '',
      userBrowser: '',
      num: 0,
      USER_ID: '',
      isRootDesigner: false,
      fullHeight: document.documentElement.clientHeight,
      fullWidth: document.documentElement.clientWidth,
      contentHei: '0px',
      rightHei: '0px',
      contentHeiNei: '0px',
      defImg: defaultImg,
      rightTopImgHei: 'auto',
      left: '0%',
      articalContent: '',
      // 接收的数据
      reciveData: {},
      ecid: '',
      // tabs切换
      expListText: true,
      expLine: true,
      lessonText: false,
      lessonLine: false,
      questionText: false,
      questionLine: false,
      commentText: false,
      commentLine: false,
      notesText: false,
      notesLine: false,
      coursewareText: false,
      coursewareLine: false,

      // 收藏
      closeIconSrc: require('../../../assets/exper/close-grey.png'),
      openIconSrc: require('../../../assets/exper/open-grey.png'),
      // 指导书展开收缩按钮的显示
      showCloseAndOpenBtn: true,
      showDataList: true,
      showDefImg: false,
      contrlImg: require('../../../assets/exper/close-book.png'),
      // 说明指导书信息
      guideList: [],
      guideSrc: '',
      showAllIframe: true,
      // 创建虚拟机
      deployWidth: '100%',
      destroyWidth: 'auto',
      createdLoad: false,
      createdVmText: '创建课件机',
      btnType: 'primary',
      ueid: '',
      proId: '',
      deployNum: '',
      destroyStatus: false,
      processText: '部署请求中...',
      //部署错误详情
      deployErrorDetailModal: false,
      errorDetailData: [],
      errorDetailColumns: [
        {
          key: 'name',
          title: '名称'
        },
        {
          key: 'type',
          title: '类型'
        },
        {
          key: 'status',
          title: '状态'
        },
        {
          key: 'operation',
          title: '操作'
        },
        {
          key: 'errorMsg',
          title: '错误信息'
        }
      ],
      leftTime: 0,
      curTime: {
        h: '00',
        m: '00',
        s: '00'
      },
      timeout: '',
      destroyInterval: '',
      errorMessage: '',
      expClassify: [],
      opVmTime: 2,
      rem: '16px',
      defaultRatio: 100,
      OffsetLeft: '0rem',
      flagEduPdf:true,
      coursewareLists:[],
      videoLists:[],
      queryCommentInfo:{
				pageIndex:1,
				pageSize:10,
				experimentId:''
			},
      commentList:[],
       notesInfo: {
        companyId: "",
        content: "",
        courseId: this.$route.query.classId,
        experimentId: "",
        level: 5,
      },
      queryNotesInfo: {
        pageIndex: 1,
        pageSize: 10,
        type: 1,
      },
      queryVideoNotesInfo: {
        pageIndex: 1,
        pageSize: 10,
        type: 2,
      },
      notesList:[],
      videoNotesList:[],
      flagAfter:false
    };
  },
  computed: {
    isOwn: function() {
      //是否是自己的（修改别人的课件不允许选择个人资源）
      return this.USER_ID == this.reciveData.createUserId;
    },
    pageTitle () {
      //当前菜单显示名
      return this.$route.meta.title;
    },
    ...mapState('style', {
        openAll: ({ themeConfig }) => {
            return themeConfig.guidebookSectionUnfoldAllImage;
        },
        closeAll: ({ themeConfig }) => {
            return themeConfig.guidebookSectionFoldAllImage;
        }
    })
  },
  async created() {
    // 获取用户id
    let November = sessionStorage.getItem('November');
    November = JSON.parse(encryption.SelfUseDecrypt(November));
    this.USER_ID = November.userId;
    this.isRootDesigner = November.isRootDesigner;
    // await this.getCoursewareList()
  },
  mounted() {
    this.setStyle();
    $('.experPage .ivu-divider-horizontal').css({
      margin: 0
    });
    $('.ivu-poptip-rel').css('width', '100%');
    window.onresize = () => {
      this.setStyle();
    };
    this.ecid = this.$route.query.ecid;
    this.classification();
    this.getExpInfo();
    //实操课件
    if (this.reciveData.expType == 0) {
      this.getDictInfoByName();
    }
    setTimeout(async ()=>{
      if(this.reciveData.guide){
        this.clickClassText('guide')
      }
      if(!this.reciveData.guide){
        this.clickClassText('courseware')
      }
      await this.getCoursewareList()
      await this.getVideoList()
      if(!this.reciveData.guide && this.coursewareLists.length==0){
        this.clickClassText('video')
      }
      if(!this.reciveData.guide && this.coursewareLists.length==0 && this.videoLists.length==0){
        this.clickClassText('question')
      }
      this.notesInfo.companyId = this.reciveData.companyId;
      this.queryCommentInfo.experimentId = this.reciveData.ecid;
      this.notesInfo.experimentId = this.reciveData.ecid;
      this.queryNotesInfo.experimentId = this.reciveData.ecid;
      this.queryVideoNotesInfo.experimentId = this.reciveData.ecid;
      await this.getCommentList()
      await this.getNotesList();
      await this.getVideoNotesList();
    },500)

  },
  beforeDestroy() {
    clearInterval(this.queryStatus);
    clearTimeout(this.destroyInterval);
  },
  beforeRouteLeave(to, from, next) {
    if (to.path === '/experiment') {
      //to.query.page = this.$route.query.page
      next();
    } else {
      //跳转至非课件页面，清空存储的查询条件
      sessionStorage.removeItem('queryObj');
      next();
    }
  },
  updated() {

  },
  methods: {
    async getCoursewareList() {
      const res = await getVideoDetail(this.reciveData.ecid, { srcType:'EduPdf' })
        this.coursewareLists = res.attribute.data;
    },
    async getVideoList() {
      const res = await getVideoDetail(this.reciveData.ecid, { srcType:'EduVideo' })
        this.videoLists = res.attribute.data;
    },
    async getCommentList(){
      const res  = await getCommentList(this.queryCommentInfo)
      this.commentList = res.data.items;
    },
    //获取文本笔记
    async getNotesList() {
      const res = await getNotesList(this.queryNotesInfo)
       this.notesList = res.data.items;
    },
    //获取视频笔记
    async getVideoNotesList() {
      const res = await getNotesList(this.queryVideoNotesInfo)
      this.videoNotesList = res.data.items;
    },
    markedData(val) {
      return marked(val);
    },
    escape2Html(str) {
      return escape2Html(str);
    },
    setStyle() {
      window.fullHeight = document.documentElement.clientHeight;
      window.fullWidth = document.documentElement.clientWidth;
      this.fullWidth = window.fullWidth;
      this.fullHeight = window.fullHeight;
      let hei = 0;
      if (this.fullWidth >= 2400) {
        // 310
        this.num = 1;
        hei = 310;
        // this.left = '457px'
      }
      if (this.fullWidth > 2200 && this.fullWidth < 2400) {
        // 250
        this.num = 2;
        hei = 250;
        // this.left = '417px'
      }
      if (this.fullWidth <= 2200 && this.fullWidth >= 1900) {
        // 225
        this.num = 3;
        hei = 225;
        //  this.left = '375px'
      }
      if (this.fullWidth > 1700 && this.fullWidth < 1900) {
        // 200
        this.num = 4;
        hei = 200;
        // this.left = '21rem'
      }
      if (this.fullWidth > 1500 && this.fullWidth <= 1700) {
        // 180
        this.num = 5;
        hei = 180;
        // this.left = '23rem'
      }
      if (this.fullWidth > 1400 && this.fullWidth <= 1500) {
        // 160
        this.num = 6;
        hei = 160;
        // this.left = '25.5rem'
      }
      if (this.fullWidth <= 1400) {
        // 140   471
        this.num = 7;
        hei = 140;
        //  this.left = '242px'
      }
      this.rightTopImgHei = hei + 'px';
      this.contentHei = this.fullHeight - 241 + 'px';
      this.contentHeiNei = this.fullHeight - 241 - 70 + 'px';
      if (this.reciveData.expType != 0) {
        this.rightHei = this.fullHeight - 170 - hei + 'px';
      } else {
        this.rightHei = this.fullHeight - 227 - hei + 'px';
      }
    },
    // 返回上一层
    returnExper() {
      // let name = 'experiment';
      // if (this.$route.query.expType == 1) {
      //   name = 'experiment';
      // } else if (this.$route.query.expType == 2) {
      //   name = 'coursewareExp';
      // } else if (this.$route.query.expType == 3) {
      //   name = 'videoExp';
      // }
      let name = this.$store.getters.pageName
      this.$router.push({
        name: name,
        query: {
          page: this.$route.query.page
        }
      });
    },
    // 获取课件详情
    getExpInfo() {
      let params = {
        eid: this.ecid
      };
      experimentDetail(params)
        .then((data) => {
          if (data.code === 1) {
            let getData = data.data;
            this.reciveData = getData;
            this.$store.commit('addBreadItem', { name: this.reciveData.ecname });
            if (this.reciveData.customType == 1) {
              this.guideSrc = `/api/minio/filePreview?path=${this.reciveData.guide}`;
            } else {
              //根据指导书ID查看是指导书是否是markdown类型
              getGuideInfoByID_new(this.ecid, this.reciveData.guide).then((res) => {
                if (res.code == 1) {
                  if (
                    res.attribute &&
                    res.attribute.data &&
                    res.attribute.data.templateid == 'markdown'
                  ) {
                    this.markType = 'markdown';
                  }
                }
              });
            }
            if (this.reciveData.expType != 2) {
              //不是文本课件
              this.getGuideFun();
            } else {
              this.coursewareText = true;
              this.coursewareLine = true;
            }
            if (this.reciveData.expType == 0) {
              //实操课件
              this.getExperStatus();
              this.setStyle();
            } else {
              this.setStyle();
            }
          } else {
            this.$Message.error({
              content: data.message,
              duration: 3
            });
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    gotoGuideFile() {
      window.openTrain(this.guideSrc, '_blank');
    },
    // 全部收起或展开
    exptaskexpand(){
        this.$refs.sectionList.exptaskexpand();
    },
    exptaskclose(){
        this.$refs.sectionList.exptaskclose();
    },
    // 切换标题栏
    clickClassText(type) {
      this.expListText = false;
      this.expLine = false;
      this.lessonText = false;
      this.lessonLine = false;
      this.questionText = false;
      this.questionLine = false;
      this.notesText = false;
      this.notesLine = false;
      this.commentText = false;
      this.commentLine = false;
      this.coursewareText = false;
      this.coursewareLine = false;
      if (type === 'guide') {
        this.expListText = true;
        this.expLine = true;
      } else if (type === 'video') {
        this.lessonText = true;
        this.lessonLine = true;
      } else if (type === 'question') {
        this.questionText = true;
        this.questionLine = true;
      } else if (type === 'comment') {
        this.commentText = true;
        this.commentLine = true;
      } else if (type === 'notes') {
        this.notesText = true;
        this.notesLine = true;
      } else if (type == 'courseware') {
        this.coursewareText = true;
        this.coursewareLine = true;
      }
    },
    // 课件指导书信息
    getGuideFun() {
      if (!this.reciveData.guide) {
        this.showDataList = false;
        this.showDefImg = true;
        return;
      }
      sectionList_new(this.ecid, this.reciveData.guide)
        .then((data) => {
          if (data.code === 1) {
            this.guideList = data.attribute.datalist;
            this.guideList.forEach((section) => {
              this.querySectionQuestion(section);
            });
            if (this.guideList.length > 0) {
              this.showDataList = true;
              this.showDefImg = false;
            } else {
              this.showDataList = false;
              this.showDefImg = true;
              console.log('1')
            }
          } else {
            this.$Message.error(data.message);
          }
          this.addAddressForImg();
        })
        .catch((err) => {
          this.$Message.error(err.data.message);
          console.log(err);
        });
    },
    querySectionQuestion(section) {
      querySectionQuestion(section.sectionid)
        .then((data) => {
          if (data.code == 1) {
            this.$set(section, 'sectionQuestionList', data.data.items);
          } else {
            this.$set(section, 'sectionQuestionList', []);
          }
        })
        .catch((error) => {
          console.log(error);
          this.$set(section, 'sectionQuestionList', []);
        });
    },
    // 图片路径
    handleImage(logo) {
      let src = '';
      if (logo) {
        if (logo.indexOf('Learn') > -1) {
          src = logo;
        } else {
          src = `/Learn/${logo}`;
        }
      } else {
        src = this.defImg;
      }
      return src;
    },
    setDefImg() {
      let img = event.srcElement;
      img.src = this.defImg;
      img.onerror = null;
    },
    // 给a标签添加跳转
    addAddressForImg() {
      this.$nextTick(() => {
        let $imgs = $('.exp a');
        for (let i = 0; i < $imgs.length; i++) {
          $imgs[i].target = '_blank';
        }
      });
    },
    // 获取课件的部署状态
    getExperStatus() {
      let path = {
        uid: this.USER_ID,
        eid: this.reciveData.ecid
      };
      expEnv(path, {})
        .then((data) => {
          let status = data.attribute.data.status;
          this.deployNum = data.attribute.data.status;
          this.proId = data.attribute.data.instanceid;
          //查询工程详情
          if (this.proId) {
            this.getProjectInfo(false);
          }
          // 新建   未部署
          if (status === 0 || status === 10) {
            // 按钮颜色 文字
            this.btnType = 'primary';
            this.deployWidth = '100%';
            this.createdVmText = '创建课件机';
          } else if (status === 3) {
            // 成功
            // 按钮颜色 文字
            this.btnType = 'success';
            this.createdVmText = '进入课件机';
            this.deployWidth = '60%';
            // 显示销毁按钮
            this.destroyWidth = '30%';
            this.destroyStatus = true;
            this.getDestroyTimeInter();
          } else if (status === 6) {
            // 失败
            // 按钮颜色 文字
            this.btnType = 'primary';
            this.createdVmText = '重新部署';
            this.deployWidth = '60%';
            // 显示销毁按钮
            this.destroyWidth = '30%';
            this.destroyStatus = true;
            this.$Message.error({ content: '部署失败!请销毁后重新部署!', duration: 10 });
          } else if (status === 9) {
            // 部署中
            this.btnType = 'primary';
            this.createdVmText = '部署中...';
            this.deployWidth = '100%';
            this.createdLoad = true;
            this.queryCreatedStatus();
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 销毁
    destroyBtn() {
      destroyExper(this.proId, this.USER_ID)
        .then((data) => {
          if (data.code == 1) {
            this.proId = '';
            this.createdLoad = false;
            // 创建按钮
            this.createdVmText = '创建课件机';
            this.btnType = 'primary';
            this.deployWidth = '100%';
            // 销毁按钮
            this.destroyStatus = false;
            this.destroyWidth = '0%';
            this.$Message.success({
              content: '销毁成功',
              duration: 3
            });
            this.deployNum = 10;
            this.processText = '0%';
            clearInterval(this.destroyInterval);
            this.errorMessage = '';
          } else {
            this.$Message.error(data.message);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 部署环境机按钮
    creatExperBtn() {
      if (this.deployNum === 3) {
        // 如果已经部署 则进入课件机
        this.showVmsListBtn();
      } else if (this.deployNum === 0 || this.deployNum === 10 || this.deployNum === 6) {
        // 未部署或部署失败
        this.deployExper();
      }
    },
    // 调用部署接口
    deployExper() {
      let formData = {
        ecId: this.reciveData.ecid,
        userId: this.USER_ID
      };
      this.createdLoad = true;
      if (this.destroyInterval) {
        clearInterval(this.destroyInterval);
      }
      creatExper(formData)
        .then((data) => {
          if (data.code === 1) {
            if (data.attribute.status && data.attribute.status === 3) {
              this.$Message.info('已有环境部署成功，请先销毁才能部署新的环境');
            } else {
              this.proId = data.attribute.projectId;
              if (this.proId) {
                this.queryCreatedStatus();
              }
            }
          } else {
            this.$Message.error({
              content: data.message,
              duration: 3
            });
            this.createdLoad = false;
          }
        })
        .catch((err) => {
          this.createdLoad = false;
          console.log(err);
        });
    },
    // 展示虚拟机列表
    showVmsListBtn() {
      const { href } = this.$router.resolve({
        path: '/testMachine',
        query: {
          projectId: this.proId,
          ecid: this.reciveData.ecid,
          teacherId: this.USER_ID
        }
      });
      window.openTrain(href, '_blank');
    },
    // 查询部署状态
    queryCreatedStatus() {
      this.queryStatus = setInterval(() => {
        queryInterval(this.proId)
          .then((data) => {
            if (data.code == 1) {
              this.processText = '部署中...' + data.attribute.progress + '%';
              if (data.attribute.progress === 100 && data.attribute.status === 3) {
                this.createdLoad = false;
                // 创建按钮
                this.createdVmText = '进入课件机';
                this.btnType = 'success';
                this.deployWidth = '60%';
                // 销毁按钮
                this.destroyWidth = '30%';
                this.destroyStatus = true;
                this.deployNum = 3;
                clearInterval(this.queryStatus);
                this.$Message.success({
                  content: '部署成功',
                  duration: 3
                });
                setTimeout(() => {
                  this.getDestroyTimeInter();
                }, 3000);
              } else if (data.attribute.progress === 100 && data.attribute.status === 6) {
                this.createdLoad = false;
                // 按钮颜色 文字
                this.btnType = 'primary';
                this.createdVmText = '重新部署';
                this.deployWidth = '60%';
                // 显示销毁按钮
                this.destroyWidth = '30%';
                this.destroyStatus = true;
                this.deployNum = 6;
                this.$Message.error({ content: '部署失败!请销毁后重新部署!', duration: 10 });
                clearInterval(this.queryStatus);
              }
            } else {
              this.createdLoad = false;
              // 按钮颜色 文字
              this.btnType = 'primary';
              this.createdVmText = '重新部署';
              this.deployWidth = '60%';
              // 显示销毁按钮
              this.destroyWidth = '30%';
              this.destroyStatus = true;
              this.deployNum = 6;
              clearInterval(this.queryStatus);
              this.$Message.error({
                content: data.message,
                duration: 3
              });
            }
            this.getProjectInfo(false); //查询错误信息
          })
          .catch((err) => {
            console.log(err);
          });
      }, 3000);
    },
    // 分享状态
    handleIsPublic(type) {
      if (type === 1 || type === '1') {
        return '单位';
      } else if (type === 0 || type === '0') {
        return '个人';
      } else if (type === 2 || type === '2') {
        return '系统';
      }
    },
    // 按钮点击状态
    setReBtnStatus() {
      let userid = this.reciveData.createUserId;
      if ((userid === this.USER_ID || this.isRootDesigner) && this.reciveData.isPublic != '2') {
        return false;
      } else {
        return true;
      }
    },
    // 困难程度
    handleDiffcult(val) {
      switch (val) {
        case 'Simple':
          return '简单';
          break;
        case 'Medium':
          return '中等';
          break;
        case 'Hard':
          return '较难';
          break;
      }
    },
    //数据字典格式化
    handleTypeCode(dictid) {
      let dictMap = {};
      this.expClassify.forEach((exp) => {
        dictMap[exp.dictid] = exp.dictname;
      });
      return dictMap[dictid];
    },
    handleDirection(dictid) {
      let type = this.expClassify.find((dict) => dict.dictid == dictid);
      let direction = '';
      if (type) {
        let aaa = this.expClassify.find((dict) => dict.dictid == type.parentid);
        if (!aaa) {
          return;
        } else {
          direction = aaa.dictname;
        }
      }
      return direction;
    },
    handleExperType(val) {
      switch (val) {
        case 0:
          return '实操课件';
          break;
        case 1:
          return '理论课件';
          break;
        case 2:
          return '文本课件';
          break;
      }
    },
    //获取工程部署错误详情
    getProjectInfo(queryDeployDetail) {
      return new Promise((resolve, reject) => {
        getstatusbyprjid(this.proId)
          .then((data) => {
            if (data.code == 1) {
              let projectInfo = data.attribute.project;
              this.projectInfo = data.attribute.project;
              this.errorMessage = data.attribute.project.errorMessage;
              if (this.errorMessage) {
                this.deployWidth = '60%';
                this.destroyWidth = '30%';
                this.createdVmText = '重新部署';
              }
              if (!this.errorMessage) {
                resolve();
              }
              //							if(queryDeployDetail){
              //								this.getProjectDeployDetail(projectInfo.deployId);
              //							}
            } else if (data.code == -2) {
              this.$Message.error('工程不存在');
            } else {
              this.$Message.error(data.message);
            }
          })
          .catch((error) => {
            console.log(error);
          });
      });
    },
    getProjectDeployDetail() {
      this.deployErrorDetailModal = true;
      let deployId = this.projectInfo.deployId;
      let params = {
        pageIndex: 1,
        pageSize: 1000,
        status: 400
      };
      getProjectDeployDetail(deployId, params)
        .then((data) => {
          if (data.code == 1) {
            this.errorDetailData = data.data.items;
          } else {
            this.errorDetailData = [];
            this.$Message.error(data.message);
          }
        })
        .catch((error) => {
          console.log(error);
        });
    },
    getDestroyTimeInter() {
      setTimeout(() => {
        //              if(!this.destroyInterval){
        clearInterval(this.destroyInterval);
        this.getDestroyTime();
        //一分钟矫正一次销毁时间
        this.destroyInterval = setInterval(() => {
          this.getDestroyTime();
        }, 1000 * 60);
        //              }
      }, 3000);
    },
    // 获取销毁时间
    getDestroyTime() {
      if(!this.proId){
        clearInterval(this.destroyInterval);
        return
      }
      getTime(this.proId)
        .then((data) => {
          if (data.code === 1) {
            this.leftTime = data.attribute.destroyTime;
            if (this.leftTime > 0) {
              this.getTimes();
            } else {
              //                                window.close();
              clearInterval(this.destroyInterval);
            }
          }
        })
        .catch((err) => {
          clearInterval(this.destroyInterval);
          console.log(err);
        });
    },
    getTimes() {
      clearTimeout(this.timeout);
      let leftTime = this.leftTime;
      if (leftTime > 0) {
        let h = Math.floor(leftTime / 1000 / 60 / 60);
        let m = Math.floor((leftTime / 1000 / 60) % 60);
        let s = Math.floor((leftTime / 1000) % 60);
        this.curTime = {
          h: h < 10 ? '0' + h : h,
          m: m < 10 ? '0' + m : m,
          s: s < 10 ? '0' + s : s
        };
        let _this = this;
        this.timeout = setTimeout(() => {
          _this.leftTime = _this.leftTime - 1000;
          _this.getTimes();
        }, 1000);
      } else {
        clearInterval(this.destroyInterval);
      }
    },
    // 获取场景分类
    classification() {
      experType()
        .then((data) => {
          if (data.code == 1) {
            let attribute = data.attribute;
            this.expClassify = attribute.attribute[0].dictEntryList;
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    getDictInfoByName() {
      getDictInfoByName({ name: 'switchToVmTime' }).then((data) => {
        if (data.code == 1) {
          this.opVmTime = data.attribute.data.defaultValue;
        }
      });
    },
    showOrHideIframe() {
      this.OffsetLeft = this.left;
      this.showAllIframe = !this.showAllIframe;
      if (this.showAllIframe) {
        this.contrlImg = require('../../../assets/exper/close-book.png');
      } else {
        this.contrlImg = require('../../../assets/exper/open-book.png');
      }
    }
  }
};
</script>
<style scoped>
@import 'github-markdown-css' .addressIcon {
  display: inline-block;
  height: 14px;
  width: 12px;
  background: url('../../../assets/exper/addressIcon.png') no-repeat center;
  background-size: 100% 100%;
  margin-bottom: -1px;
}
.class-top {
  display: flex;
  justify-content: space-between;
  padding: 0 30px;
}
.class-title-wrap {
  display: flex;
  justify-content: flex-start;
  align-items: center;
}
.class-title {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-right: 50px;
}
.class-title-all {
  font-size: 16px;
  cursor: pointer;
  color: var(--default-color-level2);
}
.active {
  color: var(--default-color);
  font-size: 22px;
  font-weight: 600;
}
.class-title-line {
  background-color: transparent;
  height: 3px;
  border-radius: 1px;
  width: 50px;
  margin: 20px 0 3px 0;
}
.line-active {
  background-color: var(--default-color);
}
.openCloseIcon {
  cursor: pointer;
}
.openCloseIcon:hover {
  color: blue;
}
/*
    * 滚动条样式
    */
.guide-wrap {
  width: 100%;
  overflow-x: hidden;
  overflow-y: auto;
  padding: 20px 30px 0px;
}
.class-right-info {
  background-color: var(--card-body-bgcolor);
  padding: 30px 20px 20px;
  border-radius: 10px;
  overflow-y: auto;
  overflow-x: hidden;
}
.difficultyIcon {
  display: inline-block;
  height: 16px;
  width: 18px;
  background: url('../../../assets/exper/deficut.png') no-repeat center;
  background-size: 11px 100%;
  margin-bottom: -2px;
  margin-right: 5px;
}
.designIcon {
  display: inline-block;
  height: 13px;
  width: 18px;
  background: url('../../../assets/exper/avtar.png') no-repeat center;
  background-size: 11px 100%;
  margin-bottom: -2px;
  margin-right: 5px;
}
.visibilyIcon {
  display: inline-block;
  height: 9px;
  width: 18px;
  background: url('../../../assets/exper/see.png') no-repeat center;
  background-size: 15px 100%;
  margin-bottom: -2px;
  margin-right: 5px;
}
.desigTimeIcon {
  display: inline-block;
  height: 11px;
  width: 18px;
  background: url('../../../assets/exper/time-icon.png') no-repeat center;
  background-size: 11px 100%;
  margin-bottom: -2px;
  margin-right: 5px;
}
.class-right-icon {
  color: darkgrey;
  line-height: 2;
  display: flex;
  align-items: center;
}
.class-right-text {
  min-width: 60px;
  width: 60px;
  display: inline-block;
  text-align-last: justify;
  color: var(--default-color-level2);
}
.class-right-icon-rule {
  color: var(--url-color);
}
.deployErrorBtn {
  font-size: 24px;
  color: #f00;
}
/deep/.destroyPop .ivu-poptip-rel {
  width: 100%;
}
.destoryTime {
  position: absolute;
  width: 100%;
  height: 40px;
  bottom: 0px;
  text-align: center;
  background: rgba(0, 0, 0, 0.6);
  padding: 8px;
  color: #fff;
}
</style>
<style>
iframe body .embedbox ::-webkit-scrollbar {
  width: 8px;
  height: 4px;
}
iframe body .embedbox ::-webkit-scrollbar-thumb {
  /*滚动条里面小方块样式*/
  border-radius: 5px;
  box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  background: rgba(209, 209, 209, 0.6);
}
iframe body .embedbox ::-webkit-scrollbar-track {
  /*滚动条里面轨道样式*/
  box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  border-radius: 5px;
  background: rgba(179, 179, 179, 0.1);
}
.iframeWarp {
  overflow: hidden;
  position: relative;
}
.iframeWarp .iframeWarpArrow {
  position: absolute;
  z-index: 20;
  top: 140px;
  color: #3a3ad1;
  font-size: 32px;
}
.iframeWarp .iframeWarpArrow.hide {
  left: 0;
}
/* .iframeWarp .iframeWarpArrow.show{
        left:21rem;
    } */
.iframeWarp .iframe {
  position: relative;
}
.iframeWarp .iframe.show {
  width: 100%;
}
.iframeWarp .iframe.hide {
  /* width:calc(100% + 21rem)!important;
        left:-21rem */
}
.class-line-div{
  width: 100%;
  height: 1px;
  background: var(--card-line-color);
  margin: 12px 0;
}
.experPage{
  height: calc(100vh - 148px);
  padding-bottom: 20px;
  overflow: hidden;
}
</style>
